/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.commons.util;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Blob;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.sql.rowset.serial.SerialBlob;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.RowSorter;
import javax.swing.border.Border;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 * 说明： 常用工具类
 * 
 * @Author：李智深
 * @Date：2012-03-14
 */
public class Util {

	// 鼠标状态
	public static Cursor CURSOR_HAND = new Cursor(Cursor.HAND_CURSOR);// 鼠标状态 手状
	public static Cursor CURSOR_DEFAULT = new Cursor(Cursor.DEFAULT_CURSOR);// 鼠标状态
																			// 默认

	public static Font TITLE_FONT = new Font("宋体", Font.BOLD, 13);
	public static Font TICKETFONT = new Font("宋体", Font.PLAIN, 6);
	public static Font TICKETFONT2 = new Font("宋体", Font.PLAIN, 5);
	public static Font TICKETFONT3 = new Font("宋体", Font.PLAIN, 8);
	public static Font TICKETFONT4 = new Font("宋体", Font.PLAIN, 30);
	public static Font FONT_PLAIN_13 = new Font("宋体", Font.PLAIN, 13);
	public static final Font FONT_14_PLAIN = new Font("宋体", Font.PLAIN, 14);
	public static final Font FONT_12_PLAIN = new Font("宋体", Font.PLAIN, 12);
	public static final Font FONT_20_PLAIN = new Font("宋体", Font.PLAIN, 20);
	public static final Font FONT_12_BOLD = new Font("宋体", Font.BOLD, 12);
	public static final Font FONT_13_BOLD = new Font("宋体", Font.BOLD, 13);
	public static final Font FONT_14_BOLD = new Font("宋体", Font.BOLD, 14);
	// 100 101 102
	public static final Color DEFAULT_TEXT_COLOR = new Color(37, 81, 54);
	public static final Color TAB_BOTTOM_LINE_COLOR = new Color(167, 173, 175);
	public static final Color CONTENT_PANE_BACKGROUND = new Color(247, 252, 255);
	public static final Color LIST_BACKGROUND = new Color(247, 252, 255);
	public static final Color LIST_TEXT_COLOR = new Color(96, 145, 192);
	public static final Color LIST_SPLIT_COLOR = new Color(105, 113, 120);
	public static final Color TABLE_HEADER_BACKGROUND_COLOR = new Color(239,
			240, 241);
	public static final Color TABLE_HEADER_BORDER_BRIGHT_COLOR = Color.white;
	public static final Color TABLE_HEADER_BORDER_DARK_COLOR = new Color(215,
			219, 223);
	public static final Color TABLE_TEXT_COLOR = new Color(74, 74, 81);
	public static final int TABLE_CELL_LEADING_SPACE = 5;
	public static final Font TABLE_HEADER_FONT = new Font("宋体", Font.PLAIN, 12);
	public static final Font TABLE_CELL_FONT = new Font("宋体", Font.PLAIN, 13);
	public static final Insets ZERO_INSETS = new Insets(0, 0, 0, 0);
	public static final Color PANEL_COLOR = new Color(244, 248, 251);

	public static final Border PANEL_BORDER = BorderFactory.createLineBorder(
			new Color(193, 197, 199), 1);

	public static final int DEFAULT_ICON_SIZE = 16;
	public static Icon BLANK_ICON = new Icon() {
		public void paintIcon(Component c, Graphics g, int x, int y) {
			// nothing.
		}

		public int getIconWidth() {
			return DEFAULT_ICON_SIZE;
		}

		public int getIconHeight() {
			return DEFAULT_ICON_SIZE;
		}
	};

	public static final int LIST_SHRINKED_WIDTH = 37;
	public static final int DEFAULT_SPLIT_WIDTH = 0;

	// 布局模式
	public static BorderLayout BorderLayout() {
		return new BorderLayout();
	}

	public static FlowLayout FlowLayout(int align) {
		return new FlowLayout(align);
	}

	// 获取屏幕宽度
	public static int getWidth() {
		return Toolkit.getDefaultToolkit().getScreenSize().width;
	}

	// 获取屏幕高度
	public static int getHeight() {
		return Toolkit.getDefaultToolkit().getScreenSize().height;
	}

	public static Dimension getDimension() {
		return new Dimension(160, 180);
	}

	// 设置主件大小
	public static void setSize(Component comp, int x, int y) {
		comp.setPreferredSize(new Dimension(x, y));
		comp.setMaximumSize(new Dimension(x, y));
		comp.setMinimumSize(new Dimension(x, y));
	}

	// 提示
	public static void showMessageDialog(String msg) {
		JOptionPane.showMessageDialog(null, msg, "提示信息",
				JOptionPane.INFORMATION_MESSAGE);
	}

	public static int showConfirmDialog(String msg) {
		return JOptionPane.showConfirmDialog(null, msg, "提示提示",
				JOptionPane.OK_CANCEL_OPTION);
	}

	// 浏览框
	private static FileDialog fileDialog;

	public static FileDialog showFileDialog(String title) {
		if (fileDialog == null) {
			fileDialog = new FileDialog(new JFrame(), title);
		}
		return fileDialog;
	}

	// 图片缩小
	public static BufferedImage rizeImage(BufferedImage srcBufImage, int width,
			int height) {
		BufferedImage bufTarget = null;
		double sx = (double) width / srcBufImage.getWidth();
		double sy = (double) height / srcBufImage.getHeight();

		int type = srcBufImage.getType();
		if (type == BufferedImage.TYPE_CUSTOM) {
			ColorModel cm = srcBufImage.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(width,
					height);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			bufTarget = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else
			bufTarget = new BufferedImage(width, height, type);

		Graphics2D g = bufTarget.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
		g.drawRenderedImage(srcBufImage, AffineTransform.getScaleInstance(sx,
				sy));
		g.dispose();
		return bufTarget;
	}

	// 图片重复绘制 图片
	public static void repeatDrawImage(Graphics2D g2d, BufferedImage bi,
			int wigth, int height, JPanel panel) {
		// 修改图片大小
		bi = rizeImage(bi, wigth, height);
		// 创建画笔
		Graphics2D big = bi.createGraphics();// 创建一个 Graphics2D，可以将它绘制到此//
												// BufferedImage 中。
		big.drawImage(bi, 0, 0, bi.getWidth(), bi.getHeight(), null);// 在缓冲区中绘制指定大小的图像
		Rectangle r = new Rectangle(0, 0, bi.getWidth(), bi.getHeight());
		TexturePaint textrue = new TexturePaint(bi, r);// 用被指定为 BufferedImage
														// 的纹理填充Shape(Rectrangle、等形状)的方式
		g2d.setPaint(textrue);// 类似于设置画笔，将textrue看作像素点
		g2d.fill(new Rectangle(0, 0, panel.getBounds().width,
				panel.getBounds().height));// 填充一个Shape
	}

	// 图片90 180 度反转
	public static BufferedImage reversalImage(BufferedImage sourceImage,
			int type) {
		AffineTransform transform = null;
		if (type == 1) {
			transform = new AffineTransform(-1, 0, 0, 1,
					sourceImage.getWidth() - 1, 0);// 水平翻转
		} else if (type == 2) {
			transform = new AffineTransform(1, 0, 0, -1, 0, sourceImage
					.getHeight() - 1);// 垂直翻转
		} else if (type == 3) {
			transform = new AffineTransform(-1, 0, 0, -1, sourceImage
					.getWidth() - 1, sourceImage.getHeight() - 1);// 旋转180度
		}
		AffineTransformOp op = new AffineTransformOp(transform,
				AffineTransformOp.TYPE_BILINEAR);
		return op.filter(sourceImage, null);
	}

	// 设置JTabel自动列宽
	public static void adjustTableColumnWidths(JTable table) {
		JTableHeader header = table.getTableHeader(); // 表头
		int rowCount = table.getRowCount(); // 表格的行数
		TableColumnModel cm = table.getColumnModel(); // 表格的列模型
		for (int i = 0; i < cm.getColumnCount(); i++) { // 循环处理每一列
			TableColumn column = cm.getColumn(i); // 第i个列对象
			int width = (int) header.getDefaultRenderer()
					.getTableCellRendererComponent(table,
							column.getIdentifier(), false, false, -1, i)
					.getPreferredSize().getWidth(); // 用表头的绘制器计算第i列表头的宽度
			for (int row = 0; row < rowCount; row++) { // 循环处理第i列的每一行，用单元格绘制器计算第i列第row行的单元格宽度
				int preferedWidth = (int) table.getCellRenderer(row, i)
						.getTableCellRendererComponent(table,
								table.getValueAt(row, i), false, false, row, i)
						.getPreferredSize().getWidth();
				width = Math.max(width, preferedWidth); // 取最大的宽度
			}
			column.setPreferredWidth(width + table.getIntercellSpacing().width); // 设置第i列的首选宽度
		}
		table.doLayout(); // 按照刚才设置的宽度重新布局各个列
	}

	// 隐藏一列
	public static void hideTableColumn(int index, JTable table) {
		TableColumn tc = table.getColumnModel().getColumn(index);
		tc.setMaxWidth(0);
		tc.setPreferredWidth(0);
		tc.setWidth(0);
		tc.setMinWidth(0);
		table.getTableHeader().getColumnModel().getColumn(index).setMaxWidth(0);
		table.getTableHeader().getColumnModel().getColumn(index).setMinWidth(0);
	}

	// 获取某列的宽度
	public static int getPreferredWidthForCloumn(JTable table, int icol) {
		TableColumnModel tcl = table.getColumnModel();
		TableColumn col = tcl.getColumn(icol);
		int c = col.getModelIndex(), width = 0, maxw = 0;
		for (int r = 0; r < table.getRowCount(); ++r) {
			TableCellRenderer renderer = table.getCellRenderer(r, c);
			Component comp = renderer.getTableCellRendererComponent(table,
					table.getValueAt(r, c), false, false, r, c);
			width = comp.getPreferredSize().width;
			maxw = width > maxw ? width : maxw;
		}
		return maxw;
	}

	// 设置JTabel自动咧宽
	public static void setJTabelAutoClumnWidth(JTable table) {
		for (int i = 0; i < table.getColumnCount(); i++) {
			int with = Util.getPreferredWidthForCloumn(table, i) + 50;
			table.getColumnModel().getColumn(i).setPreferredWidth(with);
		}
	}

	// Tip提示
	public static void postToolTip(JComponent comp) {
		Action action = comp.getActionMap().get("postTip");
		if (action == null)
			return;
		ActionEvent ae = new ActionEvent(comp, ActionEvent.ACTION_PERFORMED,
				"postTip", EventQueue.getMostRecentEventTime(), 0);
		action.actionPerformed(ae);
	}

	// Tip隐藏
	public static void hideToolTip(JComponent comp) {
		Action action = comp.getActionMap().get("hideTip");
		if (action == null)
			return;
		ActionEvent ae = new ActionEvent(comp, ActionEvent.ACTION_PERFORMED,
				"hideTip", EventQueue.getMostRecentEventTime(), 0);
		action.actionPerformed(ae);
	}

	// 将tab键变成Enter键
	public static void ENTERKeyStroke() {
		Set<KeyStroke> forwardKeySet = new HashSet<KeyStroke>();
		forwardKeySet.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
		KeyboardFocusManager.getCurrentKeyboardFocusManager()
				.setDefaultFocusTraversalKeys(
						KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
						forwardKeySet);
		Set<KeyStroke> backwardKeySet = new HashSet<KeyStroke>();
		backwardKeySet.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,
				KeyEvent.SHIFT_MASK));
		KeyboardFocusManager.getCurrentKeyboardFocusManager()
				.setDefaultFocusTraversalKeys(
						KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
						backwardKeySet);
	}

	public static String setMnemonic(javax.swing.JComponent component,
			int keyCode, int modifiers, javax.swing.AbstractAction action) {
		String mapKey = Long.toHexString(System.currentTimeMillis());
		javax.swing.ActionMap actionMap = component.getActionMap();
		actionMap.put(mapKey, action);
		javax.swing.KeyStroke keyStroke = javax.swing.KeyStroke.getKeyStroke(
				keyCode, modifiers);
		javax.swing.InputMap inputMap = component
				.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW);
		inputMap.put(keyStroke, mapKey);
		return mapKey;
	}

	// //打开浏览器
	// public static void runBroswer(String webSite) {
	// try {
	// Desktop desktop = Desktop.getDesktop();//启动已在本机桌面上注册的关联应用程序，如
	// ：浏览器，mail，print
	// if (desktop.isDesktopSupported()
	// && desktop.isSupported(Desktop.Action.BROWSE)) {
	// URI uri = new URI(webSite);
	// desktop.browse(uri);//默认的浏览器去打开
	// //desktop.open(file) 也可以打开文件
	// }
	// } catch (IOException ex) {
	// ex.printStackTrace();
	// } catch (URISyntaxException ex) {
	// ex.printStackTrace();
	// }
	// }
	// 获取所有打印机
	public static List<String> getAllPrinter() {
		List<String> pList = new ArrayList<String>();
		PrintService pss[] = PrintServiceLookup.lookupPrintServices(
				DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
		if (pss.length == 0)
			return pList;
		for (int i = 0; i < pss.length; i++) {
			pList.add(pss[i].getName());
		}

		return pList;
	}

	// 保留几位小数
	public static double DoubleHowMany(int num, double dou) {
		if (num <= 0)
			return (int) dou;
		String str = "###.";
		for (int i = 0; i < num; ++i)
			str += "0";
		DecimalFormat df = new DecimalFormat(str);// 保留一位小数
		return Double.parseDouble(df.format(dou));
	}

	public static void setButtonStatus(JToolBar toolBar, JButton button) {
		if (toolBar.getComponentCount() != 0) {
			for (int i = 0; i < toolBar.getComponentCount(); i++) {
				if (toolBar.getComponent(i) instanceof JButton) {
					((JButton) toolBar.getComponent(i)).setBorder(BorderFactory
							.createEmptyBorder());
				}
			}
		}
		button.setBorder(BorderFactory.createBevelBorder(1));
	}

	public static TexturePaint createTexturePaint(Image image) {
		int imageWidth = image.getWidth(null);
		int imageHeight = image.getHeight(null);
		BufferedImage bi = new BufferedImage(imageWidth, imageHeight,
				BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2d = bi.createGraphics();
		g2d.drawImage(image, 0, 0, null);
		g2d.dispose();
		return new TexturePaint(bi,
				new Rectangle(0, 0, imageWidth, imageHeight));
	}

	// 打开浏览器
	public static void runBroswer(String webSite) {
		try {
			Desktop desktop = Desktop.getDesktop();// 启动已在本机桌面上注册的关联应用程序，如
			// ：浏览器，mail，print
			if (desktop.isDesktopSupported()
					&& desktop.isSupported(Desktop.Action.BROWSE)) {
				URI uri = new URI(webSite);
				desktop.browse(uri);// 默认的浏览器去打开
				// desktop.open(file) 也可以打开文件
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (URISyntaxException ex) {
			ex.printStackTrace();
		}

	}

	/***
	 * 清除JTable数据
	 *****/
	public static synchronized void clearTableRowSorter(JTable table) {
		RowSorter rowSort = table.getRowSorter();
		if (rowSort != null) {
			rowSort.setSortKeys(null);// 如果使用了排序器，先清除对表的排序
		}
	}

	// Blob to image
	public static BufferedImage BlobToImage(Blob blob) {
		BufferedImage img = null;
		try {
			if (blob == null || blob.length() <= 0) {
				return null;
			}
			img = ImageIO.read(blob.getBinaryStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return img;
	}

	// image to Blob
	public static Blob ImageToBlob(BufferedImage img) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		SerialBlob blob = null;
		try {
			ImageIO.write(img, "jpg", bos);
			blob = new SerialBlob(bos.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return blob;
	}

	public static Window getTopWindow(Component comp) {
		if (comp != null) {
			while (comp.getParent() != null) {
				comp = comp.getParent();
			}
		}
		return (Window) comp;
	}

	public static void setTableColumnWidths(JTable table, int column, int width) {
		TableColumn firsetColumn = table.getColumnModel().getColumn(column);
		firsetColumn.setPreferredWidth(width);
		firsetColumn.setMaxWidth(width);
		firsetColumn.setMinWidth(width);
	}

}
